package com.centaline.androidsalesblog.rx.database;

import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.model.databaseobject.HistoryContactDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;

/**
 * 获取最近联系人
 * Created by guilin on 16/3/14.
 */
final class HistoryStaffsGetOnSubscribe implements Observable.OnSubscribe<ArrayList<StaffDo>> {

    @Override
    public void call(Subscriber<? super ArrayList<StaffDo>> subscriber) {
        ArrayList<StaffDo> result = new ArrayList<>();
        List<HistoryContactDo> historyContactDos = DataSupport.where("cityCode = ?", AppConstant.CityCode)
                .order("date desc").find(HistoryContactDo.class);
        if (historyContactDos != null &&
                historyContactDos.size() > 0) {
            final StringBuilder sql = new StringBuilder();
            sql.append("(");
            for (HistoryContactDo historyContactDo : historyContactDos) {
                sql.append("'")
                        .append(historyContactDo.getStaffNo())
                        .append("'")
                        .append(",");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
            final List<StaffDo> temp = DataSupport.where(String.format(Locale.CHINA, "cityCode = ? and staffNo in %s", sql.toString())
                    , AppConstant.CityCode).order("id desc").find(StaffDo.class);
            if (temp != null) {
                result.addAll(temp);
            }
        }
        if (!subscriber.isUnsubscribed()) {
            subscriber.onNext(result);
        }
        subscriber.onCompleted();
    }
}
